package com.psbc.online_xdclass.service.impl;

import com.psbc.online_xdclass.config.CacheKeyManager;
import com.psbc.online_xdclass.model.entity.Video;
import com.psbc.online_xdclass.model.entity.VideoBanner;
import com.psbc.online_xdclass.mapper.VideoMapper;
import com.psbc.online_xdclass.service.VideoService;
import com.psbc.online_xdclass.utils.BaseCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class VideoServiceImpl implements VideoService {
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private BaseCache baseCache;
    /**
     * 查询所有的视频列表
     * @return
     */
    @Override
    public List<Video> listVideo() {
        try{
           Object cacheObj = baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_VIDEO_KEY,()->{
                List<Video> videoList = videoMapper.listVideo();
                return videoList;
            });
           if (cacheObj instanceof List){
               List<Video> videoList = (List<Video>) cacheObj;
               return videoList;
           }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询视频列表轮播图
     * @return
     */
    @Override
    public List<VideoBanner> listBanner() {
        try{
            //这个是返回的缓存数据 cacheObj
           Object cacheObj = baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_BANNER_KEY,()->{
                List<VideoBanner> bannerList = videoMapper.listBanner();
                System.out.println("从数据库里找轮播图");
                return bannerList;
            });
           //对缓存数据进行强转
           if (cacheObj instanceof List){
               List<VideoBanner> bannerList = (List<VideoBanner>) cacheObj;
               return bannerList;
           }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据视频id查询视频的详细信息
     * @param videoId
     * @return
     */
    @Override
    public Video findDetailById(int videoId) {
        String videoDetailKey = String.format(CacheKeyManager.VIDEO_DETAIL,videoId);
        try{
           Object cacheObj = baseCache.getOneHourCache().get(videoDetailKey,()->{
                Video videoDetail = videoMapper.findDetailById(videoId);
                return videoDetail;
            });
            if (cacheObj instanceof Video){
                Video videoDetail = (Video) cacheObj;
                return videoDetail;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
